package alimarket

import (
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/text/gstr"
	"wxgf/library/easyResponse"
)

var (
	userHandlerFunc UserHandlerFunc
)

func Init(s *ghttp.Server, userHandler UserHandlerFunc, routeGroupHandler RouteGroupHandlerFunc) {
	userHandlerFunc = userHandler
	// 注入路由（该路由对客户不可见，由API网关转发）
	s.Group("/api/affiliates/alimarket/tasks", func(group *ghttp.RouterGroup) {
		group.Middleware(middlewareAuthorize)
		if routeGroupHandler != nil {
			routeGroupHandler(group)
		}
	})
}

func middlewareAuthorize(r *ghttp.Request) {
	// X-XXX-XXX 的header都是对客户不可见的，由 API网关增加

	secret := r.Header.Get("X-Secret-Key") // 密钥，在API网关配置
	if secret != xSecretKey {
		easyResponse.New(r).ResponseUnauthorized("invalid secret key")
	}

	appId := r.Header.Get("X-Ca-App-Id")
	appKey := r.Header.Get("X-Ca-App-Key")

	if appId == "" || appKey == "" {
		easyResponse.New(r).ResponseBadRequest("invalid app id or app key")
	}

	requestId := r.Header.Get("X-Ca-Request-Id")
	if requestId == "" || gstr.LenRune(requestId) != 36 {
		easyResponse.New(r).ResponseBadRequest("invalid request id")
	}

	user := &UserInfo{
		ApiKey:    "alimarkt" + appId,
		Channel:   "alimarket",
		Remark:    appKey,
		RequestId: requestId,
	}
	if userHandlerFunc != nil {
		userHandlerFunc(r.Context(), user)
	}
	r.Header.Set("X-API-Key", user.ApiKey)

	r.Middleware.Next()
}
